var gulp        = require('gulp');
var browserSync = require('browser-sync').create();//实时监控文件
var autoprefixer = require('gulp-autoprefixer');//样式兼容
var minifyCss=require('gulp-minify-css');//压缩整理css样式
var less = require('gulp-less');//解析less样式文件
var rename = require('gulp-rename');//更改文件名字
var concat = require('gulp-concat');//合并文件
var uglify=require("gulp-uglify");//检测js错误
var imagemin = require('gulp-imagemin');//压缩图片
var clean = require('gulp-clean');//删除文件
var contentIncluder = require('gulp-content-includer');//合并组件
var base64 = require('gulp-base64');//小图片转为base64

/*合并html模块*/
gulp.task('concat',function() {
    gulp.src("demo/html/*.html")
    .pipe(contentIncluder({
        includerReg:/<!\-\-include\s+"([^"]+)"\-\->/g
    }))
    .pipe(gulp.dest('dist/html'));
});

/*解析less*/
gulp.task('csslin', function () {
		return gulp.src('demo/css/less/*.less')
		.pipe(less())
		.pipe(autoprefixer({
			browsers: ['last 3 versions','Android >= 4.0'],
			cascade: false
		}))
		.pipe(gulp.dest('dist/css'))
});

/*压缩js*/
gulp.task('jsmin',function(){
		return gulp.src('demo/js/*js')
		.pipe(uglify())
		.pipe(gulp.dest("dist/js"));
	})
	

/*压缩css*/
gulp.task('cssmin', function () {
	gulp.src('demo/css/*.css')
	.pipe(minifyCss({
		advanced: false,//类型：Boolean 默认：true [是否开启高级优化（合并选择器等）]
		compatibility: 'ie7',//类型：String 默认：''or'*' [启用兼容模式； 'ie7'：IE7兼容模式，'ie8'：IE8兼容模式，'*'：IE9+兼容模式]
		keepBreaks: true//类型：Boolean 默认：false [是否保留换行]
	}))
    .pipe(base64({
        baseDir: 'public',
        extensions: ['svg', 'png', /\.jpg#datauri$/i],
        exclude:    [/\.server\.(com|net)\/dynamic\//, '--live.jpg'],
        maxImageSize: 8*1024, // bytes 
        debug: true
    }))
	.pipe(gulp.dest('dist/css'));
	
});


/*压缩图片*/
gulp.task('testImagemin', function () {
    gulp.src('demo/images/*.{png,jpg,gif,ico}')
        .pipe(imagemin({
            optimizationLevel: 3, //类型：Number  默认：3  取值范围：0-7（优化等级）
            progressive: true, //类型：Boolean 默认：false 无损压缩jpg图片
            interlaced: true, //类型：Boolean 默认：false 隔行扫描gif进行渲染
            multipass: true //类型：Boolean 默认：false 多次优化svg直到完全优化
        }))
        .pipe(gulp.dest('dist/images'));
});

/*
监控实时刷新页面*/
gulp.task('serve', function() {
    browserSync.init({
        server:{
               baseDir:"demo"
               }
    });
    gulp.watch("demo/js/*.js",['jsmin']).on('change',browserSync.reload);
    gulp.watch("demo/images/*.{png,jpg,gif,ico}",['testImagemin']).on('change',browserSync.reload);
    gulp.watch("demo/css/*.css",['cssmin']).on('change',browserSync.reload);
    gulp.watch("demo/html/*.html",['concat']).on('change',browserSync.reload);
	gulp.watch("demo/html/component/*.html",['concat']).on('change',browserSync.reload);
});



gulp.task('default',function(){
     gulp.start('cssmin','jsmin','serve','concat','testImagemin');
     });
